package com.mxin.image.glide;

import android.content.Context;
import android.graphics.Bitmap;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.FutureTarget;


import java.io.ByteArrayOutputStream;

import androidx.core.content.res.ResourcesCompat;

public class GlideUtil {
    public static byte[] syncLoad(Context mContext, String url, String type) {
        boolean isGif = type.endsWith("gif");
        if (isGif) {
            try {
                FutureTarget<byte[]> target = GlideApp.with(mContext)
                        .as(byte[].class)
                        .load(url)
                        .error(ResourcesCompat.getDrawable(mContext.getResources(), android.R.color.darker_gray, mContext.getTheme()))
                        .decode(GifDrawable.class).submit();
                return target.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        FutureTarget<Bitmap> target = Glide.with(mContext)
                .asBitmap().load(url).error(ResourcesCompat.getDrawable(mContext.getResources(), android.R.color.darker_gray, mContext.getTheme())).submit();
        try {
            Bitmap bitmap = target.get();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}